package me.wangqu.weiyouqu.web.rest.util;

import main.java.com.UpYun;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by arcticfox on 5/18/16.
 */
public class UpYunHelper {

    private static final String PATH = "/wyq";
    private static final String BASE = "http://a.weiyouqu.cc";
    private static final UpYun upyun;

    static {
        upyun = new UpYun("avatar0", "wangqu", "MLNQat3R8biEMF");
        upyun.setDebug(false); // DEBUG 模式, 默认为false
        upyun.setTimeout(30); // 超时时间, 默认30秒
        upyun.setApiDomain(UpYun.ED_AUTO); // 设置自动选择最优接入点
        // 创建目录，自动创建父级目录
//        boolean result = upyun.mkDir(PATH, true);
    }

    /**
     * 判断文件是否存在
     *
     * @param filePath
     * @return
     */
    public boolean fileExist(String filePath) {
        Map<String, String> map = upyun.getFileInfo(filePath);
        return map == null ? false : true;
    }

    /**
     * 删除文件
     *
     * @param filePath
     * @return
     */
    public boolean deleteFile(String filePath) {
        return upyun.deleteFile(filePath);
    }

    public String uploadFile(File file, String filename) {
        // 例2：采用数据流模式上传文件（节省内存）,自动创建父级目录
        String url = null;
        try {
            String filePath = PATH.concat(File.separator).concat(filename);
            upyun.setContentMD5(UpYun.md5(file));
            boolean result = upyun.writeFile(filePath, file, true);
            if (result) {
                url = BASE.concat(filePath).concat("!/format/jpg");
            }
        } catch (IOException e) {
            url = null;
        } finally {
            if (url != null) {
                return url;
            }
        }
        return null;
    }

    public String uploadImage(File file, String filename) {
        // 例2：采用数据流模式上传文件（节省内存）,自动创建父级目录
        String url = null;
        Map<String, String> params = new HashMap<String, String>();
        try {
            String filePath = PATH.concat(File.separator).concat(filename);
            upyun.setContentMD5(UpYun.md5(file));
            boolean result = upyun.writeFile(filePath, file, true, params);
            if (result) {
                url = BASE.concat(filePath);
            }
        } catch (IOException e) {
            url = null;
        } finally {
            if (url != null) {
                return url;
            }
        }
        return null;
    }
}
